<template>
  <div class="user-list">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="page-title">
        <h1>{{ $t('Identity.Users') }}</h1>
        <p class="page-description">{{ $t('Identity.UsersDescription') }}</p>
      </div>
      <div class="page-actions">
        <el-button
          v-if="hasCreatePermission"
          type="primary"
          @click="showCreateDialog"
        >
          <el-icon><Plus /></el-icon>
          {{ $t('Identity.CreateNew') }}
        </el-button>
        <el-button
          v-if="hasImportPermission"
          @click="showImportDialog"
        >
          <el-icon><Upload /></el-icon>
          {{ $t('Identity.Import') }}
        </el-button>
        <el-button v-if="hasExportPermission" @click="handleExportCommand">
          <el-icon><Download /></el-icon>
          {{ $t('Identity.Export') }}
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards" v-if="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.totalUsers }}</h3>
                <p>{{ $t('Identity.TotalUsers') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.activeUsers }}</h3>
                <p>{{ $t('Identity.ActiveUsers') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon locked">
                <el-icon><Lock /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.lockedUsers }}</h3>
                <p>{{ $t('Identity.LockedUsers') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon two-factor">
                <el-icon><Key /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.twoFactorEnabledUsers }}</h3>
                <p>{{ $t('Identity.TwoFactorEnabled') }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item :label="$t('Identity.Search')">
          <el-input
            v-model="searchForm.filter"
            :placeholder="$t('Identity.SearchPlaceholder')"
            clearable
            @clear="handleSearch"
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('Identity.Status')">
          <el-select
            v-model="searchForm.isActive"
            :placeholder="$t('Identity.AllStatus')"
            clearable
            @change="handleSearch"
          >
            <el-option :label="$t('Identity.Active')" :value="true" />
            <el-option :label="$t('Identity.Inactive')" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Identity.Role')">
          <el-select
            v-model="searchForm.role"
            :placeholder="$t('Identity.AllRoles')"
            clearable
            filterable
            @change="handleSearch"
          >
            <el-option
              v-for="role in availableRoles"
              :key="role.name"
              :label="role.displayName || role.name"
              :value="role.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Identity.Tenant')">
          <el-select
            v-model="searchForm.tenantId"
            :placeholder="$t('Identity.AllTenants')"
            clearable
            filterable
            @change="handleSearch"
          >
            <el-option
              v-for="tenant in availableTenants"
              :key="tenant.id"
              :label="tenant.displayName"
              :value="tenant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            {{ $t('Common.Search') }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            {{ $t('Common.Reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>{{ $t('Identity.UserList') }}</span>
          <div class="table-actions">
            <el-tooltip :content="$t('Common.Refresh')">
              <el-button circle @click="loadUsers">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip :content="$t('Common.ColumnSettings')">
              <el-button circle @click="showColumnSettings">
                <el-icon><Setting /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="users"
        stripe
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="userName"
          :label="$t('Identity.UserName')"
          sortable="custom"
          min-width="150"
        >
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar">
                {{ (row.name || row.surname || row.userName).charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ row.userName }}</div>
                <div class="name">{{ row.name }} {{ row.surname }}</div>
                <div class="email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          :label="$t('Identity.Roles')"
          min-width="150"
        >
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles?.slice(0, 2)"
              :key="role"
              size="small"
              style="margin-right: 4px"
            >
              {{ role }}
            </el-tag>
            <el-tag
              v-if="row.roles?.length > 2"
              size="small"
              type="info"
            >
              +{{ row.roles.length - 2 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="tenantName"
          :label="$t('Identity.Tenant')"
          min-width="120"
        >
          <template #default="{ row }">
            <el-tag v-if="row.tenantName" size="small" type="warning">
              {{ row.tenantName }}
            </el-tag>
            <span v-else class="text-muted">{{ $t('Identity.Host') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="phoneNumber"
          :label="$t('Identity.PhoneNumber')"
          width="130"
        >
          <template #default="{ row }">
            <span v-if="row.phoneNumber">{{ row.phoneNumber }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="twoFactorEnabled"
          :label="$t('Identity.TwoFactor')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="row.twoFactorEnabled ? 'success' : 'info'"
              size="small"
            >
              {{ row.twoFactorEnabled ? $t('Identity.Enabled') : $t('Identity.Disabled') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="isActive"
          :label="$t('Identity.Status')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'" size="small">
              {{ row.isActive ? $t('Identity.Active') : $t('Identity.Inactive') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastLoginTime"
          :label="$t('Identity.LastLogin')"
          sortable="custom"
          width="180"
        >
          <template #default="{ row }">
            <span v-if="row.lastLoginTime">
              {{ formatDateTime(row.lastLoginTime) }}
            </span>
            <span v-else class="text-muted">{{ $t('Identity.Never') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creationTime"
          :label="$t('Identity.CreationTime')"
          sortable="custom"
          width="180"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.creationTime) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('Common.Actions')"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip :content="$t('Common.View')">
                <el-button
                  size="small"
                  @click="viewUser(row.id)"
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip :content="$t('Common.Edit')" v-if="hasUpdatePermission">
                <el-button
                  size="small"
                  type="primary"
                  @click="editUser(row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-dropdown @command="(command) => handleUserAction(command, row)">
                <el-button size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      command="permissions"
                      v-if="hasPermissionPermission"
                    >
                      <el-icon><Key /></el-icon>
                      {{ $t('Identity.ManagePermissions') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="roles"
                      v-if="hasRolePermission"
                    >
                      <el-icon><UserFilled /></el-icon>
                      {{ $t('Identity.ManageRoles') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="password"
                      v-if="hasPasswordPermission"
                    >
                      <el-icon><Lock /></el-icon>
                      {{ $t('Identity.ChangePassword') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="twoFactor"
                      v-if="hasTwoFactorPermission"
                    >
                      <el-icon><Iphone /></el-icon>
                      {{ $t('Identity.TwoFactorSettings') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="sessions"
                      v-if="hasSessionPermission"
                    >
                      <el-icon><Monitor /></el-icon>
                      {{ $t('Identity.ManageSessions') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="loginHistory"
                      v-if="hasAuditPermission"
                    >
                      <el-icon><Clock /></el-icon>
                      {{ $t('Identity.LoginHistory') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="sync"
                      v-if="hasSyncPermission"
                    >
                      <el-icon><Refresh /></el-icon>
                      {{ $t('Identity.SyncToKeycloak') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      :divided="true"
                      command="activate"
                      v-if="hasUpdatePermission && !row.isActive"
                    >
                      <el-icon><Check /></el-icon>
                      {{ $t('Identity.Activate') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="deactivate"
                      v-if="hasUpdatePermission && row.isActive"
                    >
                      <el-icon><Close /></el-icon>
                      {{ $t('Identity.Deactivate') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="lock"
                      v-if="hasUpdatePermission && !row.lockoutEnabled"
                    >
                      <el-icon><Lock /></el-icon>
                      {{ $t('Identity.LockUser') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="unlock"
                      v-if="hasUpdatePermission && row.lockoutEnabled"
                    >
                      <el-icon><Unlock /></el-icon>
                      {{ $t('Identity.UnlockUser') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="delete"
                      v-if="hasDeletePermission"
                    >
                      <el-icon><Delete /></el-icon>
                      {{ $t('Common.Delete') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 批量操作栏 -->
    <div v-if="selectedUsers.length > 0" class="bulk-actions">
      <el-card>
        <div class="bulk-actions-content">
          <span>{{ $t('Common.Selected') }}: {{ selectedUsers.length }}</span>
          <div class="bulk-actions-buttons">
            <el-button
              @click="showBulkOperationDialog"
            >
              <el-icon><Operation /></el-icon>
              {{ $t('Common.BulkOperation') }}
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

  <!-- 用户创建/编辑对话框 -->
    <UserForm
      v-model="formDialogVisible"
      :user="editingUser"
      @success="handleFormSuccess"
    />

    <!-- 权限管理对话框 -->
    <PermissionDialog
      v-model="permissionDialogVisible"
      entity-type="user"
      :entity-id="currentEntityId"
      :entity-name="currentEntityName"
      @success="handlePermissionSuccess"
    />

    <!-- 会话管理对话框 -->
    <SessionDialog
      v-model="sessionDialogVisible"
      :user-id="currentEntityId"
      :user-name="currentEntityName"
      @session-revoked="handleSessionRevoked"
    />

    <!-- 批量操作对话框 -->
    <BulkOperationDialog
      v-model="bulkOperationDialogVisible"
      entity-type="user"
      :selected-items="selectedUsers"
      @success="handleBulkOperationSuccess"
    />

    <!-- 导入导出对话框 -->
    <ImportExportDialog
      v-model="importDialogVisible"
      entity-type="user"
      :selected-items="selectedUsers"
      @success="handleImportExportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Upload, Download, ArrowDown, Search, Refresh, Setting,
  User, Check, Lock, Key, View, Edit, MoreFilled, UserFilled,
  Iphone, Monitor, Clock, Unlock, Delete, Operation
} from '@element-plus/icons-vue'
import type { User as UserType, Role } from '@/types/abp'
import { userService } from '@/services/user.service'
import { tenantService } from '@/services/tenant.service'
import { permissionService } from '@/services/permission.service'
import { authService } from '@/services/AuthService'
import { abpService } from '@/services/abp.service'

// 导入子组件
import UserForm from '@/components/users/UserForm.vue'
import PermissionDialog from '@/components/common/PermissionDialog.vue'
import SessionDialog from '@/components/users/SessionDialog.vue'
import BulkOperationDialog from '@/components/common/BulkOperationDialog.vue'
import ImportExportDialog from '@/components/common/ImportExportDialog.vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const users = ref<UserType[]>([])
const statistics = ref<any>(null)
const selectedUsers = ref<UserType[]>([])
const availableRoles = ref<Role[]>([])
const availableTenants = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  filter: '',
  isActive: undefined,
  role: '',
  tenantId: '',
  sorting: '',
  skipCount: 0,
  maxResultCount: 20
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const formDialogVisible = ref(false)
const importDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const sessionDialogVisible = ref(false)
const bulkOperationDialogVisible = ref(false)

// 编辑/查看的用户
const editingUser = ref<UserType | null>(null)
const currentEntityId = ref<string>('')
const currentEntityName = ref<string>('')

// 权限检查
const hasCreatePermission = computed(() =>
  abpService.hasPermission('Identity.Users.Create')
)
const hasUpdatePermission = computed(() =>
  abpService.hasPermission('Identity.Users.Update')
)
const hasDeletePermission = computed(() =>
  abpService.hasPermission('Identity.Users.Delete')
)
const hasImportPermission = computed(() =>
  abpService.hasPermission('Identity.Users.Import')
)
const hasExportPermission = computed(() =>
  abpService.hasPermission('Identity.Users.Export')
)
const hasPermissionPermission = computed(() =>
  abpService.hasPermission('Identity.Users.ManagePermissions')
)
const hasRolePermission = computed(() =>
  abpService.hasPermission('Identity.Users.ManageRoles')
)
const hasPasswordPermission = computed(() =>
  abpService.hasPermission('Identity.Users.ResetPassword')
)
const hasTwoFactorPermission = computed(() =>
  abpService.hasPermission('Identity.Users.ManageTwoFactor')
)
const hasSessionPermission = computed(() =>
  abpService.hasPermission('Identity.Users.ManageSessions')
)
const hasAuditPermission = computed(() =>
  abpService.hasPermission('Identity.Users.ViewAuditLogs')
)
const hasSyncPermission = computed(() =>
  abpService.hasPermission('Identity.Users.Sync')
)

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadStatistics(),
    loadAvailableRoles(),
    loadAvailableTenants()
  ])

  // 检查URL参数
  if (route.query.tenantId) {
    searchForm.tenantId = route.query.tenantId as string
  }

  await loadUsers()
})

// 监听路由变化
watch(() => route.query.tenantId, (newTenantId) => {
  if (newTenantId !== searchForm.tenantId) {
    searchForm.tenantId = newTenantId as string
    pagination.page = 1
    loadUsers()
  }
})

// 方法
const loadStatistics = async () => {
  try {
    statistics.value = await userService.getUserStatistics()
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
}

const loadAvailableRoles = async () => {
  try {
    const result = await permissionService.getRoles({ maxResultCount: 1000 })
    availableRoles.value = result.items
  } catch (error) {
    console.error('加载角色列表失败:', error)
  }
}

const loadAvailableTenants = async () => {
  try {
    const result = await tenantService.getTenants({ maxResultCount: 1000 })
    availableTenants.value = result.items
  } catch (error) {
    console.error('加载租户列表失败:', error)
  }
}

const loadUsers = async () => {
  try {
    loading.value = true

    const params = {
      ...searchForm,
      skipCount: (pagination.page - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    }

    const result = await userService.getUsers(params)
    users.value = result.items
    pagination.total = result.totalCount
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadUsers()
}

const handleReset = () => {
  Object.assign(searchForm, {
    filter: '',
    isActive: undefined,
    role: '',
    tenantId: ''
  })
  pagination.page = 1
  loadUsers()
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  if (order) {
    searchForm.sorting = `${prop} ${order === 'ascending' ? 'asc' : 'desc'}`
  } else {
    searchForm.sorting = ''
  }
  loadUsers()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadUsers()
}

const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadUsers()
}

const handleSelectionChange = (selection: UserType[]) => {
  selectedUsers.value = selection
}

// 操作方法
const showCreateDialog = () => {
  editingUser.value = null
  formDialogVisible.value = true
}

const showImportDialog = () => {
  importDialogVisible.value = true
}

const showBulkOperationDialog = () => {
  bulkOperationDialogVisible.value = true
}

const showColumnSettings = () => {
  ElMessage.info('列设置功能开发中...')
}

const viewUser = (id: string) => {
  viewingUserId.value = id
  detailDialogVisible.value = true
}

const editUser = (user: UserType) => {
  editingUser.value = { ...user }
  formDialogVisible.value = true
}

const handleUserAction = async (command: string, user: UserType) => {
  switch (command) {
    case 'permissions':
      currentEntityId.value = user.id
      currentEntityName.value = user.userName
      permissionDialogVisible.value = true
      break
    case 'sessions':
      currentEntityId.value = user.id
      currentEntityName.value = user.userName
      sessionDialogVisible.value = true
      break
    case 'loginHistory':
      // 可以跳转到登录历史页面或显示对话框
      ElMessage.info('登录历史功能开发中...')
      break
    case 'sync':
      await syncUserToKeycloak(user.id)
      break
    case 'activate':
      await activateUser(user.id)
      break
    case 'deactivate':
      await deactivateUser(user.id)
      break
    case 'lock':
      await lockUser(user.id)
      break
    case 'unlock':
      await unlockUser(user.id)
      break
    case 'delete':
      await deleteUser(user)
      break
  }
}

const syncUserToKeycloak = async (userId: string) => {
  try {
    await userService.syncToKeycloak(userId)
    ElMessage.success('用户同步到Keycloak成功')
  } catch (error) {
    ElMessage.error('用户同步失败')
  }
}

const activateUser = async (userId: string) => {
  try {
    await userService.activateUser(userId)
    ElMessage.success('用户激活成功')
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('用户激活失败')
  }
}

const deactivateUser = async (userId: string) => {
  try {
    await userService.deactivateUser(userId)
    ElMessage.success('用户停用成功')
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('用户停用失败')
  }
}

const lockUser = async (userId: string) => {
  try {
    await userService.lockUser(userId)
    ElMessage.success('用户锁定成功')
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('用户锁定失败')
  }
}

const unlockUser = async (userId: string) => {
  try {
    await userService.unlockUser(userId)
    ElMessage.success('用户解锁成功')
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('用户解锁失败')
  }
}

const deleteUser = async (user: UserType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.userName}" 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userService.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUsers()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户删除失败')
    }
  }
}

// 批量操作
const bulkActivate = async () => {
  try {
    await userService.bulkOperation({
      userIds: selectedUsers.value.map(u => u.id),
      operation: 'Activate'
    })
    ElMessage.success('批量激活成功')
    selectedUsers.value = []
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('批量激活失败')
  }
}

const bulkDeactivate = async () => {
  try {
    await userService.bulkOperation({
      userIds: selectedUsers.value.map(u => u.id),
      operation: 'Deactivate'
    })
    ElMessage.success('批量停用成功')
    selectedUsers.value = []
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('批量停用失败')
  }
}

const bulkLock = async () => {
  try {
    await userService.bulkOperation({
      userIds: selectedUsers.value.map(u => u.id),
      operation: 'Lock'
    })
    ElMessage.success('批量锁定成功')
    selectedUsers.value = []
    loadUsers()
    loadStatistics()
  } catch (error) {
    ElMessage.error('批量锁定失败')
  }
}

const bulkDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userService.bulkOperation({
      userIds: selectedUsers.value.map(u => u.id),
      operation: 'Delete'
    })
    ElMessage.success('批量删除成功')
    selectedUsers.value = []
    loadUsers()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出功能
const handleExportCommand = () => {
  importDialogVisible.value = true
}

// 事件处理
const handleFormSuccess = () => {
  loadUsers()
  loadStatistics()
}

const handlePermissionSuccess = () => {
  ElMessage.success('权限更新成功')
  permissionDialogVisible.value = false
}

const handleSessionRevoked = () => {
  ElMessage.success('会话已撤销')
  loadUsers() // 重新加载用户列表以更新状态
}

const handleBulkOperationSuccess = () => {
  loadUsers()
  selectedUsers.value = []
  bulkOperationDialogVisible.value = false
}

const handleImportExportSuccess = (result: any) => {
  if (result.type === 'import') {
    loadUsers()
    loadStatistics()
  }
  importDialogVisible.value = false
  ElMessage.success(`${result.type === 'import' ? '导入' : '导出'}完成`)
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.page-actions {
  display: flex;
  gap: 12px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-icon.locked {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.stat-icon.two-factor {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.stat-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.user-details .username {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.user-details .name {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.user-details .email {
  font-size: 11px;
  color: #999;
  margin-top: 2px;
}

.text-muted {
  color: #999;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.bulk-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.bulk-actions-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.bulk-actions-buttons {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .page-actions {
    justify-content: center;
  }

  .statistics-cards .el-col {
    margin-bottom: 16px;
  }

  .search-card .el-form {
    flex-direction: column;
  }

  .search-card .el-form-item {
    margin-bottom: 16px;
    margin-right: 0;
  }

  .bulk-actions {
    position: static;
    transform: none;
    margin-bottom: 20px;
  }

  .user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>